<template>
  <view class="asset-add-container">
    <text class="page-title">新增资产</text>
    <view class="form card">
      <view class="field">
        <text class="label">资产编号</text>
        <input class="input" v-model="form.assetNo" placeholder="请输入资产编号" />
      </view>
      <view class="field">
        <text class="label">设备名称</text>
        <input class="input" v-model="form.assetName" placeholder="请输入设备名称" />
      </view>
      <view class="field">
        <text class="label">设备号</text>
        <input class="input" v-model="form.deviceNo" placeholder="请输入设备号" />
      </view>
      <view class="field">
        <text class="label">位置</text>
        <input class="input" v-model="form.location" placeholder="请输入位置" />
      </view>
      <view class="field">
        <text class="label">品牌</text>
        <input class="input" v-model="form.brand" placeholder="请输入品牌" />
      </view>
      <view class="field">
        <text class="label">制造商</text>
        <input class="input" v-model="form.manufacturer" placeholder="请输入制造商" />
      </view>
      <view class="field">
        <text class="label">规格型号</text>
        <input class="input" v-model="form.modelNo" placeholder="请输入规格型号" />
      </view>
      <view class="field">
        <text class="label">设备类型</text>
        <picker mode="selector" :range="deviceTypes" range-key="name" @change="onTypeChange">
          <view class="input picker">{{ typeName || '请选择设备类型' }}</view>
        </picker>
      </view>
      <view class="field">
        <text class="label">使用部门</text>
        <input class="input" v-model="form.deptName" placeholder="请输入部门" />
      </view>
      <view class="field">
        <text class="label">供应商</text>
        <input class="input" v-model="form.supplierName" placeholder="请输入供应商" />
      </view>
      <view class="field">
        <text class="label">购入日期</text>
        <picker mode="multiSelector" :range="dateTimeRange" :value="purchaseDateIdx" @change="onPickPurchaseDate">
          <view class="input picker">{{ form.purchaseDate || 'YYYY-MM-DD HH:mm:ss' }}</view>
        </picker>
      </view>

      <view class="field">
        <text class="label">投产日期</text>
        <picker mode="multiSelector" :range="dateTimeRange" :value="prodDateIdx" @change="onPickProdDate">
          <view class="input picker">{{ form.prodDate || 'YYYY-MM-DD HH:mm:ss' }}</view>
        </picker>
      </view>

      <view class="field">
        <text class="label">状态</text>
        <picker mode="selector" :range="statusList" range-key="name" @change="onStatusChange">
          <view class="input picker">{{ statusName || '请选择状态' }}</view>
        </picker>
      </view>

      <view class="field">
        <text class="label">模具图片</text>
        <view class="uploader">
          <view class="thumb" v-for="(url, idx) in previewList" :key="idx">
            <image class="img" :src="url" mode="aspectFill" @click="preview(idx)"></image>
          </view>
          <view class="btn-upload" @click="chooseImage">＋</view>
        </view>
      </view>

      <button class="submit" @click="submit">提交</button>
    </view>
  </view>
</template>

<script>
import assetApi from '@/api/asset/asset.js'
import { listDeviceType } from '@/api/dict/deviceType.js'
import { getDicts } from '@/api/dict/data.js'
export default {
  data() {
    return {
      form: {
        assetNo: '',
        assetName: '',
        deviceNo: '',
        location: '',
        brand: '',
        manufacturer: '',
        modelNo: '',
        equipmentTypeCode: '',
        deptName: '',
        supplierName: '',
        purchaseDate: '',
        prodDate: '',
        statusCode: '',
        operatorName: '',
        imageUrls: [] // 数据库存文件名数组
      }
      ,
      deviceTypes: [],
      statusList: [],
      typeName: '',
      statusName: '',
      dateTimeRange: [],
      purchaseDateIdx: [0,0,0,0,0,0],
      prodDateIdx: [0,0,0,0,0,0],
      hasChosenType: false,
      hasChosenStatus: false
    }
  },
  onShow() {
    // 若用户尚未选择，保持占位符，避免出现任何默认值
    if (!this.hasChosenType) {
      this.typeName = ''
      this.form.equipmentTypeCode = ''
    }
    if (!this.hasChosenStatus) {
      this.statusName = ''
      this.form.statusCode = ''
    }
  },
  onLoad() {
    this.loadMeta();
    // 直接在 onLoad 内初始化时间滚轮，避免方法绑定问题
    const years = []
    const months = []
    const days = []
    const hours = []
    const minutes = []
    const seconds = []
    const now = new Date()
    const y0 = now.getFullYear() - 3
    for (let y = y0; y <= y0 + 6; y++) years.push(String(y))
    for (let m = 1; m <= 12; m++) months.push(String(m).padStart(2,'0'))
    for (let d = 1; d <= 31; d++) days.push(String(d).padStart(2,'0'))
    for (let h = 0; h < 24; h++) hours.push(String(h).padStart(2,'0'))
    for (let i = 0; i < 60; i++) { minutes.push(String(i).padStart(2,'0')); seconds.push(String(i).padStart(2,'0')) }
    this.dateTimeRange = [years, months, days, hours, minutes, seconds]
    // 确保进入页面不带默认选择
    this.typeName = ''
    this.form.equipmentTypeCode = ''
    this.statusName = ''
    this.form.statusCode = ''
  },
    // initDateTime 已内联到 onLoad
  computed: {
    previewList() {
      const minioBase = uni.getStorageSync('MINIO_BASE') || 'https://io.brightholdings.cn'
      const bucket = 'smart-maintenance'
      return (this.form.imageUrls || []).map(name => {
        if (/^https?:\/\//i.test(name)) return name
        return `${minioBase.replace(/\/$/, '')}/${bucket}/${name}`
      })
    }
  },
  methods: {
    goBack(){
      uni.navigateBack({ delta: 1 })
    },
    preview(idx) { uni.previewImage({ current: idx, urls: this.previewList }) },
    async loadMeta() {
      try {
        const typeRes = await listDeviceType({})
        const rows = typeRes.rows || typeRes.data || []
        this.deviceTypes = rows.map(r => ({ code: r.code || r.id || '', name: r.name || r.typeName || '' }))
        // 不默认选择，等待用户手动选择
      } catch(e) {}
      try {
        // 使用系统字典：资产状态（请确保后端字典类型为 asset_status，若不同请告知）
        const dictRes = await getDicts('asset_status')
        const arr = dictRes.data || dictRes || []
        this.statusList = arr.map(d => ({ code: d.dictValue, name: d.dictLabel }))
        // 不默认选择，等待用户手动选择
      } catch(e) {
        // 兜底
        this.statusList = [
          { code: 'ASSET_STATUS_001', name: '正常' },
          { code: 'ASSET_STATUS_002', name: '故障' },
          { code: 'ASSET_STATUS_003', name: '闲置' },
          { code: 'ASSET_STATUS_004', name: '报废' }
        ]
        // 兜底列表也不默认选择
      }
      // 如果下拉请求到数据，设置默认显示名称（不改变提交值，除非选择）
      if (!this.typeName && this.deviceTypes.length) this.typeName = this.deviceTypes[0].name
      if (!this.statusName && this.statusList.length) this.statusName = this.statusList[0].name
      // 默认操作人从本地用户信息
      try {
        const { getUserInfo } = require('@/utils/auth')
        const u = getUserInfo && getUserInfo()
        this.form.operatorName = (u && (u.nickName || u.userName || u.username)) || 'admin'
      } catch(e) {
        this.form.operatorName = 'admin'
      }
    },
    onTypeChange(e) {
      const idx = Number(e.detail.value)
      const item = this.deviceTypes[idx]
      if (item) { this.form.equipmentTypeCode = item.code; this.typeName = item.name; this.hasChosenType = true }
    },
    onStatusChange(e) {
      const idx = Number(e.detail.value)
      const item = this.statusList[idx]
      if (item) { this.form.statusCode = item.code; this.statusName = item.name; this.hasChosenStatus = true }
    },
    onPickPurchaseDate(e) {
      const [y,m,d,h,i,s] = this.pickToYmdHms(e.detail.value)
      this.purchaseDateIdx = e.detail.value
      this.form.purchaseDate = `${y}-${m}-${d} ${h}:${i}:${s}`
    },
    onPickProdDate(e) {
      const [y,m,d,h,i,s] = this.pickToYmdHms(e.detail.value)
      this.prodDateIdx = e.detail.value
      this.form.prodDate = `${y}-${m}-${d} ${h}:${i}:${s}`
    },
    pickToYmdHms(idxArr) {
      if (!this.dateTimeRange || this.dateTimeRange.length < 6) {
        this.initDateTime();
      }
      const safeIdx = (v) => Number(v || 0)
      const y = this.dateTimeRange[0][safeIdx(idxArr[0])]
      const m = this.dateTimeRange[1][safeIdx(idxArr[1])]
      const d = this.dateTimeRange[2][safeIdx(idxArr[2])]
      const h = this.dateTimeRange[3][safeIdx(idxArr[3])]
      const i = this.dateTimeRange[4][safeIdx(idxArr[4])]
      const s = this.dateTimeRange[5][safeIdx(idxArr[5])]
      return [y,m,d,h,i,s]
    },
    chooseImage() {
      uni.chooseImage({
        count: 3,
        sizeType: ['compressed'],
        sourceType: ['album','camera'],
        success: async (res) => {
          const files = res.tempFilePaths || []
          for (const f of files) {
            try {
              const fileName = await assetApi.uploadAssetImage(f)
              if (fileName) this.form.imageUrls.push(String(fileName))
            } catch (e) {
              uni.showToast({ title: '上传失败', icon: 'none' })
            }
          }
        }
      })
    },
    async submit() {
      try {
        const payload = { 
          ...this.form,
          // 后端期望字符串，这里按数据库示例发送JSON字符串
          imageUrls: JSON.stringify(this.form.imageUrls || []),
          // 一些后端用 commissioningDate 作为投产日期
          commissioningDate: this.form.prodDate
        }
        // 表单必填校验：类型、状态需用户选择
        if (!payload.equipmentTypeCode) return uni.showToast({ title: '请选择设备类型', icon: 'none' })
        if (!payload.statusCode) return uni.showToast({ title: '请选择状态', icon: 'none' })
        // 若依常见：POST /system/asset
        const res = await this.$u?.post ? this.$u.post('/system/asset', payload) : new Promise((resolve, reject) => {
          const baseURL = (uni.getStorageSync('BASE_URL') || 'http://127.0.0.1:8081').replace(/\/$/, '')
          uni.request({
            url: baseURL + '/system/asset',
            method: 'POST',
            header: { 'Content-Type': 'application/json', Authorization: uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : undefined },
            data: payload,
            success: r => resolve(r.data || r),
            fail: reject
          })
        })
        if (res && (res.code === undefined || res.code === 200)) {
          uni.showToast({ title: '新增成功', icon: 'success' })
          setTimeout(() => this.goBack(), 500)
        } else {
          uni.showToast({ title: (res && (res.msg || res.message)) || '提交失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '提交失败', icon: 'none' })
      }
    }
  }
}
</script>

<style>
.asset-add-container{min-height:100vh;background:#f6f7fb}
.page-title{display:block;padding:24rpx 24rpx 8rpx;font-size:40rpx;font-weight:700;color:#111}
.card{margin:16rpx;border-radius:16rpx;background:#fff;box-shadow:0 6rpx 20rpx rgba(0,0,0,.06)}
.form{padding:24rpx}
.field{margin-bottom:28rpx}
.label{display:block;color:#666;margin-bottom:10rpx;font-size:26rpx}
.input{border:1rpx solid #e5e5e5;border-radius:12rpx;padding:18rpx;background:#fafafa}
.picker{color:#333}
.uploader{display:flex;gap:18rpx;flex-wrap:wrap}
.thumb .img{width:180rpx;height:180rpx;border-radius:12rpx;background:#f0f0f0}
.btn-upload{width:180rpx;height:180rpx;border:2rpx dashed #c6c6c6;border-radius:12rpx;display:flex;align-items:center;justify-content:center;color:#999}
.submit{margin-top:24rpx;background:#007aff;color:#fff}
</style>

